#!/usr/bin/python3
# coding=utf-8

# 在macOS, python3.8下测试通过. 需要pip安装一些依赖包, 见import.
# 可以配置个alias: 
# alias z='/path/to/this/jump.py'
# 然后 `z model10` 即可
# 这个脚本用于safe3环境机器.

import re, os, sys, time, json
import pexpect, struct, fcntl, termios, signal

user_name = "tianzhipeng-jk" #登录堡垒机的用户名
jumper_server_1 = "10.16.50.51" #堡垒机的ip
jumper_port_1 = 2222 #堡垒机的端口
pin_password = "466399"  #pin码, 拼接完整密码的前半部分
server_user_name = "j-tianzhipeng-jk" #登录服务器的用户名
server_password = "360_tzpABCD4" #登录服务器的密码
server_no = '16' #跳板机序号 我直接选择跳到client27了, 对应序号16. 不同人可能不同.

server_2_dict = {
    "doris28": "doris28.jinrong.lycc.qihoo.net",
    "graphmeta1": "graphmeta1.jinrong.lycc.qihoo.net",
    "graphmeta2": "graphmeta2.jinrong.lycc.qihoo.net",
    "graphmeta3": "graphmeta3.jinrong.lycc.qihoo.net",
    "model10": "model10.jinrong.lycc.qihoo.net",
    "n01": "n01.dataai.lycc.qihoo.net",
    "n02": "n02.dataai.lycc.qihoo.net",
    "n03": "n03.dataai.lycc.qihoo.net",
}

def get_terminal_size():
    s = struct.pack("HHHH", 0, 0, 0, 0)
    a = struct.unpack("hhhh", fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ, s))
    return a[0], a[1]

def sigwinch_passthrough(sig, data):
    global p
    if not p.closed:
        p.setwinsize(*get_terminal_size())

def strange_sendline(p, str):
    for c in str:
        p.send(c)
    time.sleep(0.2)
    p.sendcontrol('m')

if __name__ == "__main__":
    if len(sys.argv) == 1:
        print("请输入服务器名")
        print(json.dumps(server_2_dict, indent=2))
        sys.exit(0)
    server_2 = sys.argv[1]
    server2_name = server_2_dict.get(server_2)
    if server2_name == None:
        server2_name = server_2

    passwd = input("推推动态码:")
    p = pexpect.spawn(
        "ssh %s@%s -p%d" % (user_name, jumper_server_1, jumper_port_1),
        encoding="utf-8",
        timeout=10,
    )
    p.expect("Password:")
    p.sendline(pin_password + passwd)
    p.expect(re.escape(">"))
    strange_sendline(p, server_no)

    p.expect(re.escape("资源'[Empty]'账户:"))
    strange_sendline(p, server_user_name)

    p.expect(re.escape("资源'" + server_user_name + "'密码:"))
    strange_sendline(p, server_password)

    p.expect(re.escape(server_user_name + "@"))
    p.sendline("ssh " + server_user_name + "@" + server2_name)
    p.expect(re.compile("password:"))
    p.sendline(server_password)
    p.expect(re.escape(server_user_name + "@"))


    # Set the window size the same of current terminal window size
    p.setwinsize(*get_terminal_size())
    # Hook the window change signal so that the pexpect window size change as well
    signal.signal(signal.SIGWINCH, sigwinch_passthrough)
    p.interact()
